<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-center-atom.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Java,JavaEE,Redis,">





  <link rel="alternate" href="/atom.xml" title="Breeze-Y" type="application/atom+xml">






<meta name="description" content="NOSQL1. NOSQL的定义 泛指非关系型数据库，意为“不仅仅是SQL”,是一种全新的数据库理念。  2. NOSQL的优点 易拓展：NOSQL的共同特点就是去掉了关系型数据库的关系特性，没有了关系型数据库中表与表之间的约束，数据与数据之间的关系，使得NOSQL的拓展性非常好，在无形之间，对架构上也带来了可拓展的能力。 高性能：NOSQL有非常高的读写能力，即使在大数据下，同样十分优秀，得益于">
<meta name="keywords" content="Java,JavaEE,Redis">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis基础">
<meta property="og:url" content="http://breezes.top/2018/07/23/Redis基础/index.html">
<meta property="og:site_name" content="Breeze-Y">
<meta property="og:description" content="NOSQL1. NOSQL的定义 泛指非关系型数据库，意为“不仅仅是SQL”,是一种全新的数据库理念。  2. NOSQL的优点 易拓展：NOSQL的共同特点就是去掉了关系型数据库的关系特性，没有了关系型数据库中表与表之间的约束，数据与数据之间的关系，使得NOSQL的拓展性非常好，在无形之间，对架构上也带来了可拓展的能力。 高性能：NOSQL有非常高的读写能力，即使在大数据下，同样十分优秀，得益于">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-11-07T02:07:26.495Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Redis基础">
<meta name="twitter:description" content="NOSQL1. NOSQL的定义 泛指非关系型数据库，意为“不仅仅是SQL”,是一种全新的数据库理念。  2. NOSQL的优点 易拓展：NOSQL的共同特点就是去掉了关系型数据库的关系特性，没有了关系型数据库中表与表之间的约束，数据与数据之间的关系，使得NOSQL的拓展性非常好，在无形之间，对架构上也带来了可拓展的能力。 高性能：NOSQL有非常高的读写能力，即使在大数据下，同样十分优秀，得益于">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://breezes.top/2018/07/23/Redis基础/">





  <title>Redis基础 | Breeze-Y</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <!-- 标签样式 -->
    <!-- <a href="https://github.com/Breeze-Y"><img style="position: absolute; top: 0; left: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_gray_6d6d6d.png" alt="Fork me on GitHub"></a> -->

    <!-- <a href="https://github.com/you"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png" alt="Fork me on GitHub"></a> -->
    <!-- <a href="https://your-url" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#fff; color:#151513; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style> -->
    <a href="https://gitee.com/yuchengxin75" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Breeze-Y</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">My blog and notes</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://breezes.top/2018/07/23/Redis基础/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="郁先森">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/bolg-logo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Breeze-Y">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Redis基础</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-07-23T18:51:36+08:00">
                2018-07-23
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/JavaEE/" itemprop="url" rel="index">
                    <span itemprop="name">JavaEE</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/JavaEE/Redis/" itemprop="url" rel="index">
                    <span itemprop="name">Redis</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量  <i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,974
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  8
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="NOSQL"><a href="#NOSQL" class="headerlink" title="NOSQL"></a>NOSQL</h2><h3 id="1-NOSQL的定义"><a href="#1-NOSQL的定义" class="headerlink" title="1. NOSQL的定义"></a>1. NOSQL的定义</h3><ul>
<li>泛指非关系型数据库，意为“不仅仅是SQL”,是一种全新的数据库理念。</li>
</ul>
<h3 id="2-NOSQL的优点"><a href="#2-NOSQL的优点" class="headerlink" title="2. NOSQL的优点"></a>2. NOSQL的优点</h3><ul>
<li>易拓展：NOSQL的共同特点就是去掉了关系型数据库的关系特性，没有了关系型数据库中表与表之间的约束，数据与数据之间的关系，使得NOSQL的拓展性非常好，在无形之间，对架构上也带来了可拓展的能力。</li>
<li>高性能：NOSQL有非常高的读写能力，即使在大数据下，同样十分优秀，得益于它的无关系性，数据库的结构简单。</li>
<li>灵活的数据模型：NOSQL不需要事先为存储的数据建立字段，可以做到随时自定义数据格式。在关系型数据库下对表字段的增，删是十分的麻烦。</li>
<li>高可用：NoSQL在不太影响性能的情况，就可以方便的实现高可用的架构。比如Cassandra，HBase模型，通过复制模型也能实现高可用。</li>
</ul>
<h2 id="Redis"><a href="#Redis" class="headerlink" title="Redis"></a>Redis</h2><h4 id="1-什么是Redis？"><a href="#1-什么是Redis？" class="headerlink" title="1. 什么是Redis？"></a>1. 什么是Redis？</h4><div class="note success ">Redis是用C语言开发的一个开源的高性能键值对（key-value）数据库，官方提供测试数据，50个并发执行100000个请求,读的速度是110000次/s,写的速度是81000次/s</div>

<h4 id="2-Redis的键值数据类型"><a href="#2-Redis的键值数据类型" class="headerlink" title="2. Redis的键值数据类型"></a>2. Redis的键值数据类型</h4><ul>
<li>字符串类型 string</li>
<li>散列类型 （哈希）hash （类似于map）</li>
<li>列表类型（字符串列表）list （类似于链表）</li>
<li>集合类型 （字符串集合）set （类似于set集合 无序 数据不能重复）</li>
<li>有序集合类型 （有序字符串集合）sorted set</li>
</ul>
<h4 id="3-应用场景"><a href="#3-应用场景" class="headerlink" title="3. 应用场景"></a>3. 应用场景</h4><ul>
<li>缓存 （数据查询、短连接、新闻内容、商品内容等等）</li>
<li>聊天室的在线好友列表 （能做到对好友上线，下线 快速反应）</li>
<li>任务队列（秒杀、抢购、12306等等，得益于redis的对高并发请求的处理）</li>
<li>应用排行榜</li>
<li>网站访问统计</li>
<li>数据过期处理（可以精确到毫秒)</li>
<li>分布式集群架构中的session分离</li>
</ul>
<h4 id="4-Redis-的常用命令"><a href="#4-Redis-的常用命令" class="headerlink" title="4. Redis 的常用命令"></a>4. Redis 的常用命令</h4><h5 id="1-string"><a href="#1-string" class="headerlink" title="1. string"></a>1. string</h5><ul>
<li><code>set key value</code>：设置一个字符串的键值对 ，如果key 已经存在 就覆盖 ，总是返回ok，例如 <code>set username “tom”</code></li>
<li><code>get key</code> : 获取一个 key 的 value，key 不存在返回（nil）例如<code>get username</code></li>
<li><code>del key</code> ： 删除一个 key 例如 <code>del username</code></li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1:6379&gt; set username "tom"</span><br><span class="line">OK</span><br><span class="line">127.0.0.1:6379&gt; get username</span><br><span class="line">"tom"</span><br><span class="line">127.0.0.1:6379&gt; del username</span><br><span class="line">(integer) 1</span><br><span class="line">127.0.0.1:6379&gt; get username</span><br><span class="line">(nil)</span><br></pre></td></tr></table></figure>
<h5 id="2-hash"><a href="#2-hash" class="headerlink" title="2. hash"></a>2. hash</h5><ul>
<li><code>hset key field value</code> 为指定的key设定field/value对（键值对）。例如 <code>hset user username &quot;tom&quot;</code></li>
<li><code>hmset key field1 value1 field2 value2 field3 value3</code> 为指定的key设定多个键值对。例如 <code>hmset user username &quot;tom&quot; password &quot;123&quot; address &quot;china&quot;</code></li>
<li><code>hget key field</code>返回指定的key中的field的值</li>
<li><code>hmget key field1 field2 field3</code>同时获取一个hash对象的多个字段值</li>
<li><code>hdel key field [field … ]</code>可以删除一个或多个字段，返回值是被删除的字段个数</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1:6379&gt; hset user username "tom"</span><br><span class="line">(integer) 1</span><br><span class="line">127.0.0.1:6379&gt; hmset user age "23" address "china" email "666@qq.com"</span><br><span class="line">OK</span><br><span class="line">127.0.0.1:6379&gt; hget user username</span><br><span class="line">"tom"</span><br><span class="line">127.0.0.1:6379&gt; hmget user username password address</span><br><span class="line">1) "tom"</span><br><span class="line">2) "123"</span><br><span class="line">3) "hn"</span><br><span class="line">127.0.0.1:6379&gt; hdel user username password</span><br><span class="line">(integer) 2</span><br></pre></td></tr></table></figure>
<h5 id="3-list"><a href="#3-list" class="headerlink" title="3. list"></a>3. list</h5><ul>
<li><code>lpush key value1 value2 value3</code>把value一个一个从左边插入最后一个插入的在最上面，<code>key</code>不存先帮你创建 然后把<code>value</code>设置进去。</li>
<li><code>rpush key value1 value2 value3</code>和<code>lpush</code>相反 把值一个一个从右边插入 最后一个插入的在最下面，<code>key</code>不存先帮你创建 然后把<code>value</code>设置进去 。</li>
<li><code>lpop key</code> 从链表的头部弹出一个元素，<code>key</code>不存在,返回<code>nil</code></li>
<li><code>rpop key</code>从链表的尾部弹出一个元素，<code>key</code>不存在,返回<code>nil</code></li>
<li><code>lpushx key value</code>从左边插入一个元素，<code>key</code>不存在不会创建，命令无效</li>
<li><code>lrange key start stop</code>获取一个列表中一定范围的值 例如 <code>lrange key 0 -1</code>可以获取<code>key</code>中所有的值</li>
<li><code>lrem key count value</code>根据参数 <code>COUNT</code>的值，移除列表中与参数 <code>VALUE</code> 相等的元素，例如<ul>
<li><code>count &gt; 0</code>: 从表头开始向表尾搜索，移除与 <code>VALUE</code> 相等的元素，数量为 <code>COUNT</code></li>
<li><code>count &lt; 0</code> : 从表尾开始向表头搜索，移除与 <code>VALUE</code>相等的元素，数量为 <code>COUNT</code> 的绝对值</li>
<li><code>count = 0</code> : 移除表中所有与 <code>VALUE</code>相等的值</li>
</ul>
</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1:6379&gt; lpush test "java" "php" "jquery" "javascript" "c++"</span><br><span class="line">(integer) 5</span><br><span class="line">127.0.0.1:6379&gt; lrange test 0 -1</span><br><span class="line">1) "c++"</span><br><span class="line">2) "javascript"</span><br><span class="line">3) "jquery"</span><br><span class="line">4) "php"</span><br><span class="line">5) "java"</span><br><span class="line">127.0.0.1:6379&gt; rpush test "python" "node.js"</span><br><span class="line">(integer) 7</span><br><span class="line">127.0.0.1:6379&gt; lrange test 0 -1</span><br><span class="line">1) "c++"</span><br><span class="line">2) "javascript"</span><br><span class="line">3) "jquery"</span><br><span class="line">4) "php"</span><br><span class="line">5) "java"</span><br><span class="line">6) "python"</span><br><span class="line">7) "node.js"</span><br><span class="line">127.0.0.1:6379&gt; lpop test</span><br><span class="line">"c++"</span><br><span class="line">127.0.0.1:6379&gt; rpop test</span><br><span class="line">"node.js"</span><br><span class="line">127.0.0.1:6379&gt; lrange test 0 -1</span><br><span class="line">1) "javascript"</span><br><span class="line">2) "jquery"</span><br><span class="line">3) "php"</span><br><span class="line">4) "java"</span><br><span class="line">5) "python"</span><br><span class="line">127.0.0.1:6379&gt; lrem test 0 "php"</span><br><span class="line">(integer) 1</span><br><span class="line">127.0.0.1:6379&gt; lrange test 0 -1</span><br><span class="line">1) "javascript"</span><br><span class="line">2) "jquery"</span><br><span class="line">3) "java"</span><br><span class="line">4) "python"</span><br></pre></td></tr></table></figure>
<h5 id="4-set"><a href="#4-set" class="headerlink" title="4. set"></a>4. set</h5><div class="note success ">可以把<code>set</code>看成无序字符集合，集合元素不能重复</div>

<ul>
<li><code>sadd key value1 value2 value3</code>向set中添加数据，如果该key的值已有则不会重复添加</li>
<li><code>smembers key</code>获取set中所有的成员</li>
<li><code>srem key member1 member2 member3</code>删除set中指定的成员</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1:6379&gt; sadd test "java" "python" "c++" "javascript"</span><br><span class="line">(integer) 4</span><br><span class="line">127.0.0.1:6379&gt; smembers test</span><br><span class="line">1) "java"</span><br><span class="line">2) "javascript"</span><br><span class="line">3) "c++"</span><br><span class="line">4) "python"</span><br><span class="line">127.0.0.1:6379&gt; sadd test "java"</span><br><span class="line">(integer) 0</span><br><span class="line">127.0.0.1:6379&gt; srem test "c++" "javascript"</span><br><span class="line">(integer) 2</span><br><span class="line">127.0.0.1:6379&gt; smembers test</span><br><span class="line">1) "python"</span><br><span class="line">2) "java"</span><br></pre></td></tr></table></figure>
<h4 id="5-Redis-通用命令"><a href="#5-Redis-通用命令" class="headerlink" title="5. Redis 通用命令"></a>5. Redis 通用命令</h4><ul>
<li><code>keys pattern</code>获取与<code>pattern</code>匹配的所有<code>key</code> ，<code>*</code> 表示 任意一个或多个字符，<code>?</code>表示任意一个字符 例如 <code>keys *</code> 表示获取所有的<code>key</code></li>
<li><code>del key1 key2 key3</code> 删除指定的<code>key</code></li>
<li><code>exists key</code>判断指定的<code>key</code> 是否存在 存在返回<code>1</code>不存在返回<code>0</code></li>
<li><code>type key</code>获取指定<code>key</code>的数据类型，<code>key</code>不存在返回<code>none</code></li>
</ul>
<h4 id="6-Redis-持久化"><a href="#6-Redis-持久化" class="headerlink" title="6. Redis 持久化"></a>6. Redis 持久化</h4><div class="note success ">由于<code>Redis</code>的数据都是存在内存中，一旦服务器宕机，或是发生其他事故，数据可能就会发生丢失，无法恢复，所以Redis提供了两种持久化机制 <code>RDB</code>，<code>AOF</code></div>

<ul>
<li><p>RDB 持久化</p>
<ul>
<li>每隔一定时间，从内存中把数据保存写入到文件中，保存起来，例如每隔一小时自动归档一次。</li>
<li>使用RDB可以保证,Redis的性能最大化，归档的文件相比于AOF来说 要小很多</li>
<li>缺点<ul>
<li>如果在自动持久化之前出现宕机，那么之前的没有来得及写入磁盘的数据就会丢失</li>
<li>RDB 是通过fork 子进程来协助完成数据的持久化工作，数据较大时，可能会出现服务器停止服务几百毫秒，甚至1秒钟</li>
</ul>
</li>
<li>系统默认的RDB 持久化配置<ul>
<li><code>save 900 1</code> 每900秒(15分钟)至少有1个key发生变化，则dump内存快照</li>
<li><code>save 300 10</code>每300秒(5分钟)至少有10个key发生变化，则dump内存快照</li>
<li><code>save 60 10000</code>每60秒(1分钟)至少有10000个key发生变化，则dump内存快照</li>
</ul>
</li>
</ul>
</li>
<li><p>AOF 持久化</p>
<div class="note success ">开启AOF,需要把<code>appendonly</code>修改成<code>yes</code> 目录下产生一个<code>appendonly.aof</code>文件</div>

<ul>
<li>Redis 提供三中同步的策略<ul>
<li>每秒同步  <code>appendfsync everysec</code></li>
<li>每修改同步（效率最低）<code>appendfsync always</code></li>
<li>不同步 <code>appendfsync no</code></li>
</ul>
</li>
<li>写入操作是append（追加）模式，因此在写入过程中即使出现宕机现象，也不会破坏日志文件中已经存在的内容</li>
<li>AOF包含一个格式清晰、易于理解的日志文件用于记录所有的修改操作</li>
<li>缺点<ul>
<li>对于相同数量的数据集而言，AOF文件通常要大于RDB文件</li>
<li>AOF在运行效率上往往会慢于RDB</li>
</ul>
</li>
</ul>
</li>
</ul>

      
    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #555;font-size:14px;">-------------The End-------------</div>
    
</div>
      
    </div>

 		<div>
	      
	        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/2018/07/23/Redis基础/">Redis基础</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 郁先森 的个人博客">郁先森</a></p>
  <p><span>发布时间:</span>2018年07月23日 - 18:07</p>
  <p><span>最后更新:</span>2019年11月07日 - 10:11</p>
  <p><span>原始链接:</span><a href="/2018/07/23/Redis基础/" title="Redis基础">http://breezes.top/2018/07/23/Redis基础/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://breezes.top/2018/07/23/Redis基础/" aria-label="复制成功！"></i></span>
  </p>
  <p> 转载请保留原文链接及作者。</p>  
 <!-- 
 <span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a>
 -->
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>

	      
	    </div>
    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag"><i class="fa fa-tag" aria-hidden="true"></i> Java</a>
          
            <a href="/tags/JavaEE/" rel="tag"><i class="fa fa-tag" aria-hidden="true"></i> JavaEE</a>
          
            <a href="/tags/Redis/" rel="tag"><i class="fa fa-tag" aria-hidden="true"></i> Redis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/07/21/时间日期类/" rel="next" title="时间日期类">
                <i class="fa fa-chevron-left"></i> 时间日期类
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/11/07/新建用户/" rel="prev" title="Linux（Centos 7） 新建用户组+用户并授权">
                Linux（Centos 7） 新建用户组+用户并授权 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/bolg-logo.jpg" alt="郁先森">
            
              <p class="site-author-name" itemprop="name">郁先森</p>
              <p class="site-description motion-element" itemprop="description">愿你生命中有够多的云翳，来造成一个美丽的黄昏</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/Breeze-Y" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/yuchengxin75" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-cloud"></i>Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/5158199232" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-heart"></i>
                推荐阅读
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href title="敬请期待" target="_blank">敬请期待</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#NOSQL"><span class="nav-number">1.</span> <span class="nav-text">NOSQL</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-NOSQL的定义"><span class="nav-number">1.1.</span> <span class="nav-text">1. NOSQL的定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-NOSQL的优点"><span class="nav-number">1.2.</span> <span class="nav-text">2. NOSQL的优点</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis"><span class="nav-number">2.</span> <span class="nav-text">Redis</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-什么是Redis？"><span class="nav-number">2.0.1.</span> <span class="nav-text">1. 什么是Redis？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-Redis的键值数据类型"><span class="nav-number">2.0.2.</span> <span class="nav-text">2. Redis的键值数据类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-应用场景"><span class="nav-number">2.0.3.</span> <span class="nav-text">3. 应用场景</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-Redis-的常用命令"><span class="nav-number">2.0.4.</span> <span class="nav-text">4. Redis 的常用命令</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-string"><span class="nav-number">2.0.4.1.</span> <span class="nav-text">1. string</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-hash"><span class="nav-number">2.0.4.2.</span> <span class="nav-text">2. hash</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-list"><span class="nav-number">2.0.4.3.</span> <span class="nav-text">3. list</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-set"><span class="nav-number">2.0.4.4.</span> <span class="nav-text">4. set</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-Redis-通用命令"><span class="nav-number">2.0.5.</span> <span class="nav-text">5. Redis 通用命令</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-Redis-持久化"><span class="nav-number">2.0.6.</span> <span class="nav-text">6. Redis 持久化</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="/js/src/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">郁先森</span>
  
  <div class="BbeiAn-info">
    <!--湘ICP备 - -->
    <a target="_blank" href="https://beian.miit.gov.cn/" style="color:#555" rel="nofollow">湘ICP备19025452号-1</a> <!--a标签中增加nofollow属性，避免爬虫出站。-->| 
    <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=44030902001850" style="color:#555;text-decoration:none;padding-left:30px;background:url(https://s1.ax1x.com/2018/09/29/ilmwIH.png) no-repeat left center" rel="nofollow">粤公网安备 44030902001850</a>    <!--这里将图标作为了背景，以使得能和后面的文字在同一行-->
  </div>

  
</div>


<!-- 
  <div class="powered-by">由  强力驱动</div>
 -->


<!-- 
  <span class="post-meta-divider">|</span>
 -->

<!-- 
  #<div class="theme-info">主题 &mdash;  v5.1.4</div> -->
<div class="theme-info">
  <span class="post-count"> 与君共勉 | 全站总字数:4.1k</span>
</div>




        
<div class="busuanzi-count">
  <script async src="/js/src/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数  <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站访问量  <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  


    
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;"></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/src/fireworks.js"></script>


</body>
</html>
<!-- <script type="text/javascript" src="/js/src/love.js"></script> -->
